package com.attendancesystem.controller;


import com.attendancesystem.service.UserService;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet(name = "DeleteUserController", urlPatterns = "DeleteUserController")
public class DeleteUserController extends HttpServlet {
  @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//      response.setContentType("application/json");
      response.setCharacterEncoding("UTF-8");
      PrintWriter out = response.getWriter();

      try {
          int userId = Integer.parseInt(request.getParameter("id"));
          System.out.println("userId:"+userId);
          UserService userService = new UserService();

          if(userService.deleteUser(userId)) {
              response.setStatus(HttpServletResponse.SC_OK);
              out.print("{\"message\":\"用户删除成功\"}");
          } else {
              response.setStatus(HttpServletResponse.SC_NOT_FOUND);
              out.print("{\"error\":\"用户不存在\"}");
          }
      } catch (NumberFormatException e) {
          response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
          out.print("{\"error\":\"无效的用户ID格式\"}");
      } finally {
          out.flush();
      }
    }
}
